import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;

class TCPServer
{
	private static int player = 0;
	private static LinkedBlockingQueue<byte[]> blockingQueue = new LinkedBlockingQueue<byte[]>();
	
	public static void main(final String argv[]) throws Exception
	{
		String clientSentence;
		String capitalizedSentence;
		ServerSocket welcomeSocket = new ServerSocket(5000);
		
		System.out.println("Serwer");

		while(true)
		{
			final Socket connectionSocket = welcomeSocket.accept();
			
			
			new Thread(new Runnable()
			{
				int me = player++;
				
				@Override
				public void run()
				{
					InputStream inFromClient;
					try
					{
						inFromClient = connectionSocket.getInputStream();
						DataOutputStream outToClient = new DataOutputStream(
								connectionSocket.getOutputStream());
						
						while (true)
						{
							byte[] cbuf = new byte[(640*480)+1];
							inFromClient.read(cbuf);
							switch(cbuf[0])
							{
							case MessageTypes.C_LOGIN:
								display(cbuf);
								outToClient.write(new byte[]{MessageTypes.S_LOGIN_OK});
								if(me == 0)
								{
									while(true)
										outToClient.write(blockingQueue.take());
								}
								
								Thread.sleep(100);
								outToClient.write(new byte[]{MessageTypes.S_PUN_FOR_DRAWER});
								break;
								
							case MessageTypes.IMAGE_MESSAGE:
								System.out.println((int)cbuf[0]+":Image message ["+me+"]");
								blockingQueue.put(cbuf);
								break;
								
							default:
								display(cbuf);
								byte[] message = { MessageTypes.CHAT_MESSAGE, 'S', ':', 'N', 'i', 'e'};
								outToClient.write(message);
								break;
								
							}
							Thread.sleep(500);
						}
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					catch (InterruptedException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
		}
	}

	private static void display(final byte[] cbuf)
	{
		for (int i = 0; i < cbuf.length; i++)
		{
			if(i==0)
				System.out.print((int)cbuf[i]+":");
			else if(cbuf[i] != 0)
				System.out.print((char)cbuf[i]);
		}		
	}
}